package com.example.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Slf4j
public class SecurityUtils {
    /*
    加密
     */
    public static String encrypt(String plaintext) {
        log.info("接收参数，plaintext: {}",plaintext);
        if (!StringUtils.hasLength(plaintext)) {
            log.error("plaintext 不合法");
            return null;
        }
        String salt = UUID.randomUUID().toString().replace("-","");
        String ciphertext = DigestUtils.md5DigestAsHex((salt + plaintext).getBytes());
        String password = "";
        password += (ciphertext.substring(0,22));
        password += (salt);
        password += (ciphertext.substring(22,32));
        return password;
    }


    /*
    解密
     */
    public static Boolean verify(String plaintext, String password) {
        log.info("接收参数，plaintext: {}, result: {}",plaintext, password);
        if (!StringUtils.hasLength(plaintext)) {
            log.error("plaintext 不合法");
            return false;
        }
        if (!StringUtils.hasLength(password) || password.length() != 64) {
            log.error("result 不合法");
            return false;
        }
        String salt = password.substring(22,54);
//        System.out.println(salt);
        String userciphertext = DigestUtils.md5DigestAsHex((salt + plaintext).getBytes());
//        System.out.println(ciphertext);
        String sqlciphertext = "";
        sqlciphertext += (password.substring(0,22));
//        System.out.println(ciphertext);
        sqlciphertext += (password.substring(54,64));
//        System.out.println(ciphertext);
        if (sqlciphertext.equals(userciphertext)) {
            return true;
        }
        return false;
    }
}
